//
//  DownLoadViewController.m
//  CapriceMusic
//
//  Created by dllo on 16/1/11.
//  Copyright © 2016年 MYX. All rights reserved.
//

#import "DownLoadViewController.h"
#import "DataBaseHandle.h"
#import "DownloadTableViewCell.h"
#import "CustomPlayerViewController.h"
#import "AppDelegate.h"
@interface DownLoadViewController ()<UITableViewDataSource, UITableViewDelegate,NSURLSessionDownloadDelegate,NSURLSessionDataDelegate>

@property (nonatomic, strong) UISegmentedControl *segmentControl;

@property (nonatomic, strong) UITableView *tableView;

@property (nonatomic, strong) NSMutableArray *downLoading;

@property (nonatomic, strong) DataBaseHandle *dataBaseHandle;

@property (nonatomic, assign) CGFloat num;

@property (nonatomic, assign) BOOL isdownloading;

@end

static DownLoadViewController *downLoadManager = nil;

@implementation DownLoadViewController


+ (instancetype)shareDownLoadManager {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        downLoadManager = [[DownLoadViewController alloc] init];
    });
    return downLoadManager;
}

- (instancetype)init {
    self = [super init];
    if (self) {
        self.segmentControl = [[UISegmentedControl alloc] initWithItems:@[@"已下载",@"正在下载"]];
        _segmentControl.frame = CGRectMake(self.view.frame.size.width / 10, 0, self.view.frame.size.width * 0.8, 30);
        _segmentControl.tintColor = [UIColor colorWithRed:30 / 255.0 green:195 / 255.0 blue:153 / 255.0 alpha:1.0];
        self.segmentControl.selectedSegmentIndex = 1;
        [self.segmentControl addTarget:self action:@selector(segmentControlDidPress) forControlEvents:UIControlEventValueChanged];
        [self.view addSubview:self.segmentControl];
        
        self.dataBaseHandle = [DataBaseHandle shareDataBase];
        [self.dataBaseHandle openDataBase];
        [self.dataBaseHandle selectdownloading];
        [self.dataBaseHandle closedDataBase];
        
        self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 35, self.view.frame.size.width, self.view.frame.size.height - 35) style:UITableViewStylePlain];
        self.tableView.delegate = self;
        self.tableView.dataSource = self;
        self.tableView.tag = 101;
        [self.tableView registerClass:[DownloadTableViewCell class] forCellReuseIdentifier:@"DownLoadingIdentifier"];
        [self.view addSubview:self.tableView];
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"下载的MV";
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (self.segmentControl.selectedSegmentIndex == 0) {
        
        return self.dataBaseHandle.downloadAlreadyAddress.count;
    } else {
    NSLog(@"个数为%d",self.dataBaseHandle.downloadingTitle.count);
    return self.dataBaseHandle.downloadingTitle.count;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    DownloadTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"DownLoadingIdentifier"];
    if (self.segmentControl.selectedSegmentIndex == 0) {
        cell.titleLabel.text = self.dataBaseHandle.downloadAlreadyTitle[indexPath.row];
        [cell.coverPic sd_setImageWithURL:[NSURL URLWithString:self.dataBaseHandle.downloadAlreadyPicture[indexPath.row]]];
        [cell.progressView removeFromSuperview];
        [cell.button removeFromSuperview];
        return cell;
    } else {
        [cell.coverPic sd_setImageWithURL:[NSURL URLWithString:self.dataBaseHandle.downloadingPicture[indexPath.row]]];
        cell.titleLabel.text = self.dataBaseHandle.downloadingTitle[indexPath.row];
        cell.progressView.progress = downLoadManager.num;
        return cell;
    }
}

- (void)segmentControlDidPress {
    self.dataBaseHandle = [DataBaseHandle shareDataBase];
    if (self.segmentControl.selectedSegmentIndex == 0) {
        [self.dataBaseHandle openDataBase];
        [self.dataBaseHandle createDownloadAlreadyTable];
        [self.dataBaseHandle selectdownloadAlready];
        [self.dataBaseHandle closedDataBase];
        [self.tableView reloadData];
    } else {
        [self.dataBaseHandle openDataBase];
        [self.dataBaseHandle createDownloadingTable];
        [self.dataBaseHandle selectdownloading];
        [self.dataBaseHandle closedDataBase];
        [self.tableView reloadData];
    }
}

/**
 *  下载完毕后调用
 *
 *
 *  @param location     文件临时地址
 */

- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location {
    NSString *caches = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
    // response.suggestedFilename ： 建议使用的文件名，一般跟服务器端的文件名一致
    NSString *file = [caches stringByAppendingPathComponent:downloadTask.response.suggestedFilename];
    // 将临时文件剪切或者复制Caches文件夹
    NSFileManager *mgr = [NSFileManager defaultManager];
    // AtPath : 剪切前的文件路径
    // ToPath : 剪切后的文件路径
    [mgr moveItemAtPath:location.path toPath:file error:nil];
    NSLog(@"%@",file);
    
    self.dataBaseHandle = [DataBaseHandle shareDataBase];
    [self.dataBaseHandle openDataBase];
    [self.dataBaseHandle createDownloadAlreadyTable];
    [self.dataBaseHandle selectdownloading];
    [self.dataBaseHandle insertDownloadAlreadyDatabase:self.dataBaseHandle.downloadingTitle.lastObject withPicture:self.dataBaseHandle.downloadingPicture.lastObject withAddress:file];
    [self.dataBaseHandle deleteDownloading:self.dataBaseHandle.downloadingTitle.lastObject];
    [self.dataBaseHandle selectdownloading];
    [self.dataBaseHandle closedDataBase];
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.tableView reloadData];
    });
}

/**
 *  每次写入沙盒完毕调用
 *  在这里面监听下载进度，totalBytesWritten/totalBytesExpectedToWrite
 *  @param bytesWritten              这次写入的大小
 *  @param totalBytesWritten         已经写入沙盒的大小
 *  @param totalBytesExpectedToWrite 文件总大小
 */
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite {
//    NSLog(@"%f",(float)totalBytesWritten/totalBytesExpectedToWrite * 100);
    downLoadManager.num = (float)totalBytesWritten/totalBytesExpectedToWrite;
       [self performSelectorOnMainThread:@selector(updataCell) withObject:nil waitUntilDone:NO];
    NSLog(@"%f",downLoadManager.num);
    UITableView *tableView = (UITableView *)[self.view viewWithTag:101];
//    for (id obj in tableView.subviews) {
//        if ([obj isKindOfClass:[DownloadTableViewCell class]]) {
//            NSLog(@"%@",obj);
//        }
//    }
}

- (void)updataCell {
    if (self.segmentControl.selectedSegmentIndex == 1) {
        UITableView *tableView = (UITableView *)[self.view viewWithTag:101];
        DownloadTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"DownLoadingIdentifier"];
        cell.progressView.progress = downLoadManager.num;
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:1 inSection:0];
        [tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationNone];

    }
}

- (void)downLoad:(NSString *)url {
    NSURL *downloadurl = [NSURL URLWithString:url];
    NSURLSessionConfiguration *cfg = [NSURLSessionConfiguration defaultSessionConfiguration];
    self.session = [NSURLSession sessionWithConfiguration:cfg delegate:self delegateQueue:[NSOperationQueue mainQueue]];
    self.downloadTask = [self.session downloadTaskWithURL:downloadurl];
    [_downloadTask resume];
    self.isdownloading = YES;
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    return YES;
}

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {
    return UITableViewCellEditingStyleDelete;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
        [self.dataBaseHandle openDataBase];
    if (self.segmentControl.selectedSegmentIndex == 0) {
        NSFileManager *fileManager = [NSFileManager defaultManager];
        [fileManager removeItemAtPath:self.dataBaseHandle.downloadAlreadyAddress[indexPath.row] error:nil];
        [self.dataBaseHandle.downloadAlreadyTitle removeObjectAtIndex:indexPath.row];
        [self.dataBaseHandle.downloadAlreadyPicture removeObjectAtIndex:indexPath.row];
        [self.dataBaseHandle deleteDownloadAlready:self.dataBaseHandle.downloadAlreadyAddress[indexPath.row]];
        [self.dataBaseHandle selectdownloadAlready];
        [self.dataBaseHandle closedDataBase];
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationTop];
    } else  {
        [self.dataBaseHandle deleteDownloading:self.dataBaseHandle.downloadingTitle[0]];
        [self.dataBaseHandle.downloadingTitle removeObjectAtIndex:indexPath.row];
        [self.dataBaseHandle.downloadingPicture removeObjectAtIndex:indexPath.row];
        [self.dataBaseHandle selectdownloading];
        [self.dataBaseHandle closedDataBase];
        [downLoadManager.downloadTask cancelByProducingResumeData:^(NSData * _Nullable resumeData) {
            [downLoadManager setResumeData:resumeData];
            downLoadManager.downloadTask = nil;
        }];
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationTop];
        self.isdownloading = NO;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return CGFLOAT_MIN;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return CGFLOAT_MIN;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (self.segmentControl.selectedSegmentIndex == 0) {
        NSLog(@"%@",self.dataBaseHandle.downloadAlreadyAddress[indexPath.row]);
        CustomPlayerViewController *custom = [CustomPlayerViewController shareSinglePlayerViewController];
        custom.urlString = self.dataBaseHandle.downloadAlreadyAddress[indexPath.row];
        
        [self presentViewController:custom animated:YES completion:^{
            [custom createPlayerView];
        }];

    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return self.view.frame.size.height / 5;
}



- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.tabBarController.tabBar.hidden = YES;
    AppDelegate *tempAppDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    [tempAppDelegate.LeftSlideVC setPanEnabled:NO];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
